package com.budwk.app.sys.services.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.services.SqfwFormSummaryService;
import com.budwk.app.sys.models.Sys_task;
import com.budwk.app.sys.services.TaskJobForCommonHandleService;
import com.budwk.app.util.poiUtils.CommonFormOfficeForAdminUtils;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: dfxy-community
 * @description: 公共业务处理定时任务服务实现
 * @author: LJT
 * @create: 2023-12-20 10:34
 **/
@IocBean(args = {"refer:dao"})
@Slf4j
public class TaskJobForCommonHandleServiceImpl extends BaseServiceImpl<Sys_task> implements TaskJobForCommonHandleService {
    public TaskJobForCommonHandleServiceImpl(Dao dao) {
        super(dao);
    }

    public static final String SERVICE_ARGS = "service_args";// 服务参数配置
    public static final String UPDATE_LOCAL_PICTURE_TIME = "update_local_picture_time";// 本地更新图片时间
    private static final SimpleDateFormat SDF_START = new SimpleDateFormat("yyyy-MM-dd 00:00:00");// 开始时间格式

    @Inject
    SqfwFormSummaryService sqfwFormSummaryService;

    ExecutorService executorService = Executors.newFixedThreadPool(20);

    /**
     * 获取服务参数
     *
     * @return
     */
    public static Map<String, String> getServiceArgs() {
        return CommonComponent.getDictMap(SERVICE_ARGS);
    }

    @Override
    public void updateLocalPictureTaskJob() {
        // 获取数据时间范围内图片URL数据
        List<String> picUrls = getSummaryPictureUrl();
        if (ObjectUtil.isEmpty(picUrls) || picUrls.size() <= 0) {
            return;
        }
        // 下载图片到本地
        try {
            for (String url : picUrls) {
                executorService.execute(() -> {
                    downloadPicture(url);
                });
            }
        } catch (Exception e) {
        } finally {
            executorService.shutdown();
        }
    }

    /**
     * 获取summary表中的时间范围内图片路径
     *
     * @return
     */
    private List<String> getSummaryPictureUrl() {
        // 获取数据时间范围
        Date startDate = DateUtil.offsetDay(DateUtil.parse(SDF_START.format(new Date())), -Integer.parseInt(getServiceArgs().get(UPDATE_LOCAL_PICTURE_TIME)));
        StringBuffer sb = new StringBuffer("SELECT a9,a10,a19,a20 FROM shequ.\"sqfw_form_summary\" WHERE create_date >= @startDate AND a9 LIKE '%/%' OR a10 LIKE '%/%' OR a19 LIKE '%/%' OR a20 LIKE '%/%' ORDER BY create_date DESC");
        Sql sql = Sqls.create(sb.toString());
        sql.setParam("startDate", startDate);
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();
                List<String> picUrls = new ArrayList<String>();
                while (rs.next()) {
                    for (int i = 0; i < columnCount; i++) {
                        String picUrlA9 = rs.getString("a9");
                        String picUrlA10 = rs.getString("a10");
                        String picUrlA19 = rs.getString("a19");
                        String picUrlA20 = rs.getString("a20");
                        if (StringUtils.isNotEmpty(picUrlA9) && picUrlA9.startsWith("/")) {
                            picUrls.add(picUrlA9);
                        }
                        if (StringUtils.isNotEmpty(picUrlA10) && picUrlA10.startsWith("/")) {
                            picUrls.add(picUrlA10);
                        }
                        if (StringUtils.isNotEmpty(picUrlA19) && picUrlA19.startsWith("/")) {
                            picUrls.add(picUrlA19);
                        }
                        if (StringUtils.isNotEmpty(picUrlA20) && picUrlA20.startsWith("/")) {
                            picUrls.add(picUrlA20);
                        }
                    }
                }
                return picUrls;
            }
        });
        sqfwFormSummaryService.execute(sql);
        return sql.getList(String.class);
    }

    private long downloadPicture(String url) {
        long picSize = 0;
        if (StringUtils.isBlank(url)) {
            return picSize;
        }
        List<String> urlList = Lists.newArrayList(url.split(","));
        if (urlList.size() == 0) {
            return picSize;
        }
        String huaweiOssPrefix = NutzIocUtils.getOssPrefix();
        for (String urlStr : urlList) {
            final String[] finalUrlStr = {urlStr};
            try {
                if (StringUtils.isNotBlank(finalUrlStr[0])) {
                    if (finalUrlStr[0].startsWith("/")) {
                        finalUrlStr[0] = huaweiOssPrefix + urlStr;
                    }
                    // 检查本地路径是否存在，如果不存在则创建对应的目录
                    String picPath = CommonFormOfficeForAdminUtils.getTempParentPictureFile(urlStr);
                    Path picAbsPath = Paths.get(picPath);
                    if (null != picAbsPath && Files.exists(picAbsPath)) {
                        // 如果文件存在就不需要重新下载
                        continue;
                    }
                    if (null != picAbsPath.getParent() && Files.notExists(picAbsPath.getParent())) {
                        // 创建所有的父目录
                        Files.createDirectories(picAbsPath.getParent());
                    }
                    HttpUtil.downloadFile(finalUrlStr[0], picPath);
                    picSize += Files.size(picAbsPath);
                    log.info("pictureDownLoad: {} To {}", finalUrlStr[0], picPath);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return picSize;
    }
}
